local nn = "`1'"
rename lprod_`nn' lA

*Random group assignment within age-ind-location-yr
sort order
gen random1= runiform()
bys S J T (random1): gen order2=_n 
bys S J T : gen RG = order2>(_N/2)

* Groups
egen TR		=group(T RG)
egen JT		=group(J T)
egen JTR	=group(J T RG)
egen ST		=group(S T)
egen STR	=group(S T RG)
egen SJT	=group(S J T)
egen SJTR	=group(S J T RG)

* Tau weights
bys SJT : egen emp_SJT	= total(empl)
bys ST	: egen emp_ST	= total(empl)
bys JT	: egen emp_JT	= total(empl)

gen empshare_SJT 		= emp_SJT/emp_ST
gen empindshare_JT 		= emp_SJT/emp_JT

egen tag_SJT	= tag(SJT)
egen tag_ST	= tag(ST)

quietly reghdfe lA [aw=empl], absorb(temp_tau=SJT) keepsingletons
quietly reghdfe temp_tau  if tag_SJT, absorb(JT) resid keepsingletons
predict tau if e(sample), resid	
			
quietly reghdfe tau [aw=empshare_SJT], absorb(capT_temp=ST)  keepsingletons
quietly reghdfe capT_temp if tag_ST, absorb(T) resid keepsingletons
predict capT if e(sample), resid


foreach var in  tau capT {
	 tempvar weight
	  gen `weight'=1
	if("`var'"=="tau"){
	  replace `weight'=empshare_SJT
	  local tag SJT
	  }
	else{
		local tag ST
	}

	_pctile `var' [aw=`weight'] ,  p(5, 15, 85, 95)
	local p5=r(r1)
	local p95=r(r4)
	local p15=r(r2)
	local p85=r(r3)
	tempvar `var'_p90 `var'_p10
	quietly sum `var' [aw=`weight'] if `var'<`p95' & `var'>=`p85' & tag_`tag'
	quietly gen ``var'_p90'=r(mean)
	quietly sum `var' [aw=`weight'] if `var'<`p15' & `var'<=`p5' & tag_`tag'
	quietly gen ``var'_p10'=r(mean)
	quietly gen p9010_`var'=``var'_p90'-``var'_p10'
}


quietly tabstat capT if tag_ST, stat(N var mean) save
matrix stats	=r(StatTotal)
gen N_capT	=stats[1,1]
gen var_capT	=stats[2,1]

quietly tabstat tau [aw=empshare_SJT] if tag_SJT, stat(N var mean) save
matrix stats	=r(StatTotal)
gen N_tau	=stats[1,1]
gen var_tau	=stats[2,1]

keep if tag_SJT
keep var*  tau  capT  p9010* S T J empshare_SJT
ren (var*  tau  capT  p9010*) =_`nn'
